<template>
  <div class="chatbot-container">
    <!-- 机器人图标 - 打开弹窗时隐藏 -->
    <div class="robot-icon" @click="toggleChatWindow" v-if="!isChatOpen">
      <i class="fas fa-robot"></i>
    </div>

    <!-- 聊天窗口 - 增大尺寸 -->
    <div class="chat-window-container" v-if="isChatOpen">
      <!-- 侧边会话列表 -->
      <div class="conversation-sidebar" v-if="showSidebar">
        <div class="sidebar-header">
          <h4>会话</h4>
        </div>
        <div class="conversation-list">
          <div
            v-for="(conv, index) in conversations"
            :key="conv.id"
            :class="[
              'conversation-item',
              conv.id === activeConversationId ? 'active' : '',
            ]"
            @click="switchConversation(index)"
          >
            <div class="conv-title">{{ conv.title }}</div>
            <button
              @click.stop="deleteConversation(index)"
              class="delete-conv-btn"
            >
              <i class="fas fa-trash-alt"></i>
            </button>
          </div>
        </div>
        <!-- 新会话按钮移到列表下方 -->
        <div class="sidebar-footer">
          <button @click="createNewConversation" class="new-conv-btn">
            <i class="fas fa-plus"></i> 新会话
          </button>
        </div>
      </div>

      <!-- 主聊天窗口 -->
      <div
        class="chat-window"
        :class="showSidebar ? 'with-sidebar' : 'without-sidebar'"
      >
        <div class="chat-header">
          <!-- 添加侧边栏控制按钮 -->
          <button @click="toggleSidebar" class="sidebar-toggle-btn">
            <i class="fas fa-bars"></i>
          </button>
          <h3>AI助手</h3>
          <button @click="toggleChatWindow" class="close-btn">&times;</button>
        </div>
        <div class="chat-messages">
          <!-- 将计算属性改为方法调用 -->
          <div
            v-for="(message, index) in getMessages()"
            :key="index"
            :class="[
              'message-container',
              message.isUser
                ? 'user-message-container'
                : 'ai-message-container',
            ]"
          >
            <div class="avatar">
              <i v-if="message.isUser" class="fas fa-user"></i>
              <i v-else class="fas fa-robot"></i>
            </div>
            <div class="message">
              <span class="content">{{ message.text }}</span>
              <div v-if="!message.isUser" class="ai-controls">
                <button
                  @click="stopResponse(index)"
                  class="control-btn stop-btn"
                  v-if="message.isGenerating"
                >
                  <i class="fas fa-stop"></i>
                </button>
                <!-- 点赞按钮仅在消息生成完成后显示 -->
                <button
                  @click="likeResponse(index)"
                  class="control-btn like-btn"
                  :class="{ liked: message.liked }"
                  v-if="message.isComplete"
                >
                  <i class="fas fa-thumbs-up"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <input
            type="text"
            v-model="userInput"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
            :disabled="isResponding"
          />
          <button @click="sendMessage" :disabled="isResponding">
            <i class="fas fa-paper-plane"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isChatOpen: false,
      // 替换原有messages数组为会话数组
      conversations: [
        {
          id: 1,
          title: this.generateDefaultTitle(),
          messages: [],
        },
      ],
      activeConversationId: 1,
      nextConvId: 2,
      userInput: "",
      isResponding: false,
      showSidebar: true, // 新增：控制侧边栏显示状态
      currentIntervalId: null, // 确保此变量已初始化
    };
  },
  methods: {
    // 生成默认会话标题
    generateDefaultTitle() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      return `会话 ${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 新增会话管理方法
    createNewConversation() {
      this.conversations.push({
        id: this.nextConvId++,
        title: this.generateDefaultTitle(),
        messages: [],
      });
      this.activeConversationId = this.nextConvId - 1;
    },
    toggleChatWindow() {
      this.isChatOpen = !this.isChatOpen;
    },
    // 移除computed属性，改为方法
    // REMOVED: nested methods object here
    getMessages() {
      const activeConv = this.conversations.find(
        (conv) => conv.id === this.activeConversationId
      );
      return activeConv ? activeConv.messages : [];
    },
    sendMessage() {
      if (!this.userInput.trim() || this.isResponding) return;

      const message = {
        text: this.userInput,
        isUser: true,
      };

      const activeConv = this.conversations.find(
        (conv) => conv.id === this.activeConversationId
      );
      if (activeConv) {
        this.$set(activeConv.messages, activeConv.messages.length, message);
      }

      this.userInput = "";
      this.isResponding = true;

      // 更新会话标题为用户第一条消息
      const activeConvIndex = this.conversations.findIndex(
        (conv) => conv.id === this.activeConversationId
      );
      // 只计算用户发送的消息数量
      const userMessages = this.conversations[
        activeConvIndex
      ].messages.filter((m) => m.isUser);
      // 当用户发送第一条消息时设置标题
      if (userMessages.length === 1) {
        // 使用message.text而非this.userInput，因为userInput已被清空
        this.$set(this.conversations[activeConvIndex], 'title', this.truncateTitle(message.text));
      }

      this.simulateAIResponse();
    },
    switchConversation(index) {
      this.activeConversationId = this.conversations[index].id;
    },
    deleteConversation(index) {
      // 确保至少保留一个会话
      if (this.conversations.length <= 1) return;

      // 如果删除的是当前会话，自动切换到第一个会话
      if (this.conversations[index].id === this.activeConversationId) {
        this.activeConversationId = this.conversations[0].id;
      }
      this.conversations.splice(index, 1);
    },
    simulateAIResponse() {
      // 创建AI响应消息
      const aiMessage = {
        text: "",
        isUser: false,
        isGenerating: true,
        isComplete: false,
        liked: false,
      };

      // 获取当前活动会话并添加AI消息
      const activeConv = this.conversations.find(
        (conv) => conv.id === this.activeConversationId
      );
      if (!activeConv) {
        console.error("未找到活动会话");
        return;
      }

      // 使用Vue.set确保响应式更新
      this.$set(activeConv.messages, activeConv.messages.length, aiMessage);

      // 模拟AI响应生成过程
      const responses = [
        "感谢您的提问！我正在分析您的问题。",
        "根据您提供的信息，我认为最佳解决方案是：",
        "这是一个复杂问题，需要从多个角度考虑。",
        "希望我的回答对您有帮助！如有其他问题，请随时提问。",
      ];

      let responseIndex = 0;
      // 清除任何现有定时器
      if (this.currentIntervalId) {
        clearInterval(this.currentIntervalId);
      }

      this.currentIntervalId = setInterval(() => {
        if (!this.isResponding) {
          clearInterval(this.currentIntervalId);
          this.$set(aiMessage, "isGenerating", false);
          this.$set(aiMessage, "isComplete", true);
          return;
        }

        if (responseIndex < responses.length) {
          // 使用Vue.set更新文本确保响应式
          this.$set(
            aiMessage,
            "text",
            aiMessage.text + responses[responseIndex]
          );
          responseIndex++;
        } else {
          clearInterval(this.currentIntervalId);
          this.isResponding = false;
          this.$set(aiMessage, "isGenerating", false);
          this.$set(aiMessage, "isComplete", true);
        }
      }, 1000);
    },
    stopResponse() {
      if (this.currentIntervalId) {
        clearInterval(this.currentIntervalId);
        this.isResponding = false;
        const activeConv = this.conversations.find(
          (conv) => conv.id === this.activeConversationId
        );
        if (activeConv && activeConv.messages.length > 0) {
          const lastMessage =
            activeConv.messages[activeConv.messages.length - 1];
          if (!lastMessage.isUser) {
            this.$set(lastMessage, "isGenerating", false);
            this.$set(lastMessage, "isComplete", true);
          }
        }
      }
    },
    likeResponse(index) {
      // 直接操作会话消息数组
      const activeConv = this.conversations.find(
        (conv) => conv.id === this.activeConversationId
      );
      if (activeConv && activeConv.messages[index]) {
        this.$set(
          activeConv.messages[index],
          "liked",
          !activeConv.messages[index].liked
        );
      }
    },
    truncateTitle(text) {
      // 将长消息截断作为会话标题
      return text.length > 20 ? text.substring(0, 20) + "..." : text;
    },
    // 新增：切换侧边栏显示状态
    toggleSidebar() {
      this.showSidebar = !this.showSidebar;
    },
  },
};
</script>

<style scoped>
.chatbot-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

.robot-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #42b983;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.chat-window {
  width: 500px; /* 进一步增大弹窗尺寸 */
  height: 650px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  background-color: #42b983;
  color: white;
  padding: 5px 15px; /* 已将上下内边距从12px减小到5px */
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px; /* 添加固定高度 */
}

.chat-header h3 {
  margin: 0; /* 移除默认margin */
  font-size: 16px; /* 可选：减小字体大小增强视觉效果 */
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

/* 修复消息容器样式 */
.message-container {
  display: flex;
  margin-bottom: 15px;
  max-width: 80%;
}

/* AI消息容器 - 左对齐 */
.ai-message-container {
  align-self: flex-start;
}

/* 用户消息容器 - 右对齐 */
.user-message-container {
  align-self: flex-end;
  flex-direction: row-reverse;
  margin-left: auto;
}

/* 修复消息气泡样式 */
.ai-message-container .message {
  background-color: white;
  border: 1px solid #e0e0e0;
  margin-left: 10px;
}

.user-message-container .message {
  background-color: #42b983;
  color: white;
  margin-right: 10px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  font-size: 16px;
}

.user-message-container .avatar {
  background-color: #42b983;
  color: white;
}

.message {
  padding: 10px 15px;
  border-radius: 18px;
  position: relative;
}

.ai-message-container .message {
  background-color: white;
  border: 1px solid #e0e0e0;
  margin-left: 10px;
}

.user-message-container .message {
  background-color: #42b983;
  color: white;
  margin-right: 10px;
}

.ai-controls {
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
  gap: 5px;
}

.control-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
  padding: 3px;
}

.control-btn:hover {
  color: #42b983;
}

.chat-input {
  display: flex;
  padding: 10px;
  border-top: 1px solid #e0e0e0;
}

.chat-input input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  outline: none;
}

.chat-input button {
  margin-left: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.control-btn.like-btn i {
  transition: color 0.2s;
}

/* 点赞状态样式 */
.control-btn.like-btn.liked i {
  color: #42b983;
}
</style>

<style scoped>
/* 会话容器样式 */
.chat-window-container {
  display: flex;
  width: 800px; /* 增大整体宽度以容纳侧边栏 */
  height: 650px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

/* 侧边栏样式 */
.conversation-sidebar {
  width: 250px;
  border-right: 1px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.sidebar-header h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.new-conv-btn {
  width: 100%;
  padding: 8px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

/* 优化删除按钮样式 */
.conversation-item {
  padding: 10px;
  margin-bottom: 5px;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  transition: all 0.2s ease;
}

.delete-conv-btn {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #999;
  font-size: 12px;
  opacity: 0;
  transition: opacity 0.2s ease, color 0.2s ease;
  padding: 3px;
}

.conversation-item:hover .delete-conv-btn {
  opacity: 1;
}

.delete-conv-btn:hover {
  color: #ff4d4f;
}

/* 调整主聊天窗口宽度 */
.chat-window {
  width: calc(100% - 250px);
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 侧边栏控制按钮样式 */
.sidebar-toggle-btn {
  background: none;
  border: none;
  color: white;
  margin-right: 10px;
  cursor: pointer;
  font-size: 16px;
}

/* 聊天窗口宽度适应侧边栏显示状态 */
.chat-window.with-sidebar {
  width: calc(100% - 250px);
}

.chat-window.without-sidebar {
  width: 100%;
}
/* 侧边栏底部样式 */
.sidebar-footer {
  padding: 10px;
  border-top: 1px solid #e0e0e0;
}
</style>
